package com.system.questionnairesurvey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.questionnairesurvey.common.util.response.R;
import com.system.questionnairesurvey.entity.mybatis.ProjectEntity;
import com.system.questionnairesurvey.entity.mybatis.QuestionEntity;
import com.system.questionnairesurvey.mapper.QuestionMapper;
import com.system.questionnairesurvey.service.QuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 问题表 服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2022-09-16
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, QuestionEntity> implements QuestionService {

    @Override
    public R updateQuestion(QuestionEntity entity) {
        if (exist(entity)) {
            return R.buildFail("问题已存在");
        }
        return R.buildSuccess(this.updateById(entity));
    }

    @Override
    public R saveQuestion(QuestionEntity entity) {
        if (exist(entity)) {
            return R.buildFail("问题已存在");
        }
        return R.buildSuccess(this.save(entity));
    }

    @Override
    public R listQuestion(String key, Integer num, Integer size) {
        PageHelper.startPage(num, size);
        List<QuestionEntity> entities = listByKeyword(key);
        return R.buildSuccess(new PageInfo<>(entities));
    }

    /**
     * 查询问题
     */
    private List<QuestionEntity> listByKeyword(String key) {
        LambdaQueryWrapper<QuestionEntity> wrapper = Wrappers.<QuestionEntity>lambdaQuery().like(QuestionEntity::getName, key);
        return this.list(wrapper);
    }

    /**
     * 是否存在
     */
    private boolean exist(QuestionEntity entity) {
        LambdaQueryWrapper<QuestionEntity> wrapper = Wrappers.<QuestionEntity>lambdaQuery()
                .ne(Objects.nonNull(entity.getId()), QuestionEntity::getId, entity.getId())
                .eq(QuestionEntity::getName, entity.getName());
        return this.getOne(wrapper) != null;
    }
}
